/*
 * @Description: 请求验证、访问过滤
 * @Autor: HuiSir<www.zuifengyun.com>
 * @Date: 2022-05-25 13:48:57
 * @LastEditTime: 2022-06-07 15:35:26
 */
import Koa from 'koa'
import Micro, { useConfig, resErr } from 'tcp-micro-service'

export default (): Koa.Middleware => {
    const { apiWhiteList, apiBlackList } = useConfig().common

    return async (ctx, next) => {
        // 白名单放行
        if (apiWhiteList.find((item: string) => ctx.originalUrl.includes(item))) {
            await next() // 注意别忘了await
            return
        }

        // 黑名单阻断
        if (apiBlackList.find((item: string) => ctx.originalUrl.includes(item))) {
            resErr.e404()
            return
        }

        /* ******* CHECK TOKEN ******** */

        // 获取token
        const token = ctx.headers['access-token']
        if (!token) {
            //没有token直接阻断
            resErr.e403()
            return
        }

        // 判断是否连接user服务
        if (!(ctx.micro as Micro).hasSocket('user')) {
            resErr.e403()
            return
        }

        // 验证token
        const res = await (ctx.micro as Micro).request({
            service: 'user',
            path: 'tokenVerify',
            method: 'SYS',
            data: { token }
        })

        console.log("===验证token", res)

        if (res.ok !== 1) {
            ctx.status = res.status
            ctx.body = res
            return
        }

        await next()
    }
}